/**
 * Copyright (C) 2007-2011 JUG Events Team <info@jugevents.org>
 *
 * This file is part of JUG Events Web Application.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package it.jugpadova.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.CaptchaServiceException;

/**
 * A validator for classes with jCaptchaCode and captchaService attributes
 *
 * @author Lucio Benfante (<a href="mailto:lucio.benfante@jugpadova.it">lucio.benfante@jugpadova.it</a>)
 */
public class JCaptchaValidator implements Validator {

    private static final Logger logger = LoggerFactory.getLogger(
            JCaptchaValidator.class);

    public JCaptchaValidator() {
    }

    @SuppressWarnings(value = "unchecked")
    public boolean supports(Class clazz) {
        return JCaptchaValidable.class.isAssignableFrom(clazz);
    }

    public void validate(Object obj, Errors errors) {
        JCaptchaValidable vobj = (JCaptchaValidable) obj;
        CaptchaService captchaService = vobj.getCaptchaService();
        String captchaId = vobj.getCaptchaId();
        String response = vobj.getCaptchaResponse();
        boolean isResponseCorrect = false;
        try {
            if (response != null) {
                isResponseCorrect = captchaService.validateResponseForID(
                        captchaId, response);
                if (!isResponseCorrect) {
                    errors.rejectValue("captchaResponse", "captchaerror",
                            "Wrong control text!");
                }
            }
        } catch (CaptchaServiceException e) {
            logger.debug("Error validating captcha field", e);
            errors.rejectValue("captchaResponse", "captchaerror",
                    "Wrong control text!");
        }
    }
}
